package cn.hahah.module.blog.service.usercode;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.hahah.module.blog.controller.admin.usercode.vo.*;
import cn.hahah.module.blog.dal.dataobject.usercode.UserCodeDO;
import cn.hahah.framework.common.pojo.PageResult;
import cn.hahah.framework.common.pojo.PageParam;
import cn.hahah.framework.common.util.object.BeanUtils;

import cn.hahah.module.blog.dal.mysql.usercode.UserCodeMapper;

import static cn.hahah.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.hahah.module.blog.enums.ErrorCodeConstants.*;

/**
 * 博客系统用户验证码 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class UserCodeServiceImpl implements UserCodeService {

    @Resource
    private UserCodeMapper userCodeMapper;

    @Override
    public Long createUserCode(UserCodeSaveReqVO createReqVO) {
        // 插入
        UserCodeDO userCode = BeanUtils.toBean(createReqVO, UserCodeDO.class);
        userCodeMapper.insert(userCode);
        // 返回
        return userCode.getId();
    }

    @Override
    public void updateUserCode(UserCodeSaveReqVO updateReqVO) {
        // 校验存在
        validateUserCodeExists(updateReqVO.getId());
        // 更新
        UserCodeDO updateObj = BeanUtils.toBean(updateReqVO, UserCodeDO.class);
        userCodeMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserCode(Long id) {
        // 校验存在
        validateUserCodeExists(id);
        // 删除
        userCodeMapper.deleteById(id);
    }

    private void validateUserCodeExists(Long id) {
        if (userCodeMapper.selectById(id) == null) {
            throw exception(USER_CODE_NOT_EXISTS);
        }
    }

    @Override
    public UserCodeDO getUserCode(Long id) {
        return userCodeMapper.selectById(id);
    }

    @Override
    public PageResult<UserCodeDO> getUserCodePage(UserCodePageReqVO pageReqVO) {
        return userCodeMapper.selectPage(pageReqVO);
    }

}